package com.shxc.smarttrade.old.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.activity.RechargeActivity;
import com.shxc.smarttrade.old.activity.StockChartUpgradeActivity;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.OpenTrader;
import com.shxc.smarttrade.old.bean.PendingOrder;
import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.bean.SymbolInfo;
import com.shxc.smarttrade.old.bean.SymbolPrice;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.iview.IViewStockChart;
import com.shxc.smarttrade.old.myview.CommonAutoRelativeLayout;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.presenter.StockChartPresenter;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.CountClass;
import com.shxc.smarttrade.old.utils.Logger;
import com.shxc.smarttrade.old.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by jcdev1 on 2017/5/25.
 */

public class StopLossOrProfitFragment extends Fragment implements IViewStockChart {
    @BindView(R.id.iv_set_lose_profit)
    ImageView ivSetLoseProfit;
    @BindView(R.id.ll_stop_lose)
    LinearLayout llStopLose;
    @BindView(R.id.ll_stop_profit)
    LinearLayout llStopProfit;
    @BindView(R.id.no_ll_orien)
    LinearLayout noLLOrien;
    @BindView(R.id.no_ll_buy_rise)
    LinearLayout noLLBuyRise;
    @BindView(R.id.no_ll_buy_fall)
    LinearLayout noLLBuyFall;
    @BindView(R.id.no_tv_buy_rise)
    TextView noTvBuyRise;
    @BindView(R.id.no_tv_buy_fall)
    TextView noTvBuyFall;
    @BindView(R.id.no_tv_center_times)
    EditText noTvCenterTimes;
    @BindView(R.id.no_tv_stop_loss_num)
    TextView noTVStopLossNum;
    @BindView(R.id.no_tv_stop_profit_num)
    TextView noTVStopProfitNum;
    @BindView(R.id.no_tv_stop_loss)
    TextView noTVStopLoss;
    @BindView(R.id.no_tv_stop_profit)
    TextView noTVStopProfit;

    @BindView(R.id.tv_margin)
    TextView tvMargin;
    @BindView(R.id.tv_loss)
    TextView tvLoss;
    @BindView(R.id.tv_profit)
    TextView tvProfit;

    @BindView(R.id.no_iv_right_add)
    ImageView noIVRightAdd;
    @BindView(R.id.no_iv_stop_loss_sub)
    ImageView noIVStopLossSub;
    @BindView(R.id.no_iv_stop_loss_add)
    ImageView noIVStopLossAdd;
    @BindView(R.id.no_iv_stop_profit_sub)
    ImageView noIVStopProfitSub;
    @BindView(R.id.no_iv_stop_profit_add)
    ImageView noIVStopProfitAdd;

    private View rootView;
    private StockChartPresenter stockChartPresenter = new StockChartPresenter(this);
    private String symbol;//英文名
    private String symbolCn;//中文名
    private double noPendingTimes;//购买手数（待提交参数volume）
    private double minVolume;//手数每次减少和增加的量
    private double stopsLevel;//止盈止损远离步长
    private double stopLossOrProfitVar;//止盈止损的变化量
    private double stopLossTotal;//止损处总的改变量
    private double stopProfitTotal;//止盈处总的改变量

    private int loadStartPos = 5500;
    private int loadEndPos = 6000;
    private int loadCount = 100;
    public boolean isSetLoseOrProfit = false;//是否设置止盈止损
    public int selectWhatNoPended = 0;//未开启挂单选择买入还是卖出 0：买入 1：卖出
    private double mStopProfit;//记录实时止盈的最值
    private double mStopLoss;//记录实时止损的最值
    private double sl = 0;//待提交参数（止损价）
    private double tp = 0;//待提交参数（止盈价）
    private double ask;//实时买价
    private double bid;//实时卖价
    private int type;//当前项目类型
    private double marginBase;//占用保证金计算基数
    //    private double price;//实时(ask+bid)/2
    private boolean marginChange = false;//保证金是否要转化成美元
    private boolean profitChange = false;//盈亏是否要转化成美元
    private boolean profitUSDPrex = false;//盈亏是否已美元为基础货币
    private boolean usdprex = false;//保证金是否已美元为基础货币
    private int contracSize;//合约数
    private double accAmt;//账户余额
    private int digits;//位数
    private String buyMax;//最大可买手数拼接的字符串
    private double handMax;//最大可买手数
    private int tag = 0;//实时数据中的标记，为了只执行一次
    private PopupWindow popupWindow;
    private StockChartUpgradeActivity activity = (StockChartUpgradeActivity) getActivity();
    private MyProgressDialog dialog;
    private String[] symbols = null;//保证金和盈亏计算所需要的不同品种英文名称
    private double[] askBidOne = null;
    private double[] askBidTwo = null;
    private double[] askBidThree = null;
    private double marginAll;//保证金总数
    private Handler handler = new Handler();
    private Runnable runnable;
    private int showTime = 5000;
    private boolean isFinishActivity = false;//是否在popupWindow消失时关闭Activity

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_stoploss_or_profit, null);
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        EventBus.getDefault().register(this);
        ButterKnife.bind(this, rootView);
        initView();
        initListener();
        return rootView;
    }

    /**
     * 初始化View
     */
    private void initView() {
        Intent intent = getActivity().getIntent();
        symbol = intent.getStringExtra("symbol");
        symbolCn = intent.getStringExtra("symbolCn");
    }

    /**
     * 监听手数的文本输入
     */
    private void initListener() {
        noTvCenterTimes.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //限制最大值和最小值
                String text = s.toString();
                int dotIndex = text.indexOf(".");
                int textLength = text.length();

                if (dotIndex == 0) {
//                    tvMargin.setText("手数格式错误");
                    return;
                }
                if (textLength - 1 == dotIndex) {
                    text = text + "00";
                }
                if (textLength - dotIndex > 3) {
                    text = text.substring(0, dotIndex + 3);
//                    tvMargin.setText("只保留小数点后两位");
                }
                double handtimes = Double.parseDouble(text);
                if (handtimes < 0.01) {
//                    tvMargin.setText("最小0.01手");
                    noPendingTimes = 0.01;
                    return;
                }
                if (handtimes > handMax) {
//                    tvMargin.setText("最大" + handMax + "手");
                    noPendingTimes = handMax;
                    return;
                }
                noPendingTimes = handtimes;

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        noTvCenterTimes.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    InputMethodManager im = (InputMethodManager) getActivity().getSystemService(getContext().INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        });

        ((StockChartUpgradeActivity) getActivity()).llAll.setOnSoftKeybordStatusListener(new CommonAutoRelativeLayout.softKeybordStatusListener() {
            @Override
            public void softKeybordStatus(boolean status) {

                if (status) {
                    noTvCenterTimes.setCursorVisible(true);
                } else {
                    noTvCenterTimes.setCursorVisible(false);
                }
            }
        });
    }

    /**
     * 防止软键盘覆盖相关内容
     */
    private void getKeyboardHeight() {
        //注册布局变化监听
        getActivity().getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //判断窗口可见区域大小
                Rect r = new Rect();
                int screenHeight = BaseUtils.getScreenHeight(getActivity());
                getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //如果屏幕高度和Window可见区域高度差值大于整个屏幕高度的1/3，则表示软键盘显示中，否则软键盘为隐藏状态。
                int heightDifference = screenHeight - (r.bottom - r.top);
                boolean isKeyboardShowing = heightDifference > screenHeight / 3;
                if (isKeyboardShowing) {
                    changeScrollView();
                    //移除布局变化监听
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        getActivity().getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        getActivity().getWindow().getDecorView().getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                }
            }
        });
    }

    private void changeScrollView() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //将ScrollView滚动到底
                ScrollView scrollView = ((StockChartUpgradeActivity) getActivity()).scrollView;
                scrollView.fullScroll(View.FOCUS_DOWN);
            }
        }, 100);
    }

    /**
     * 实时数据，由Activity提供
     */
    public void setRealTimeDatas(List<RealTimeQuoteDatas.DataBean.QuoteBean> quoteBeen) {
        int quoteBeenSize = quoteBeen.size();
        if (quoteBeen != null && quoteBeenSize > 0) {
            if (noTvBuyRise == null) return;
            for (int i = 0; i < quoteBeenSize; i++) {
                String curSymbol = quoteBeen.get(i).getSymbol();
                if (curSymbol.equals(symbol)) {
                    ask = quoteBeen.get(i).getAsk();
                    bid = quoteBeen.get(i).getBid();
                    askBidOne = new double[]{ask, bid};
                }
                if (symbols != null && curSymbol.equals(symbols[1])) {
                    askBidTwo = new double[]{quoteBeen.get(i).getAsk(), quoteBeen.get(i).getBid()};
                }
                if (symbols != null && curSymbol.equals(symbols[2])) {
                    askBidThree = new double[]{quoteBeen.get(i).getAsk(), quoteBeen.get(i).getBid()};
                }
            }
//             else {
//                //用于展示页面上的的基本数据
//                ask = quoteBeen.get(0).getAsk();
//                bid = quoteBeen.get(0).getBid();
//                askBidOne = new double[]{ask, bid};
//            }


//            price = Arith.div(Arith.add(ask, bid), 2, digits);
            if (noTvBuyRise != null)
                noTvBuyRise.setText(ask + "");
            if (noTvBuyFall != null)
                noTvBuyFall.setText(bid + "");

            //当开启止盈止损时
            if (isSetLoseOrProfit) {
                if (selectWhatNoPended == 0) {
                    //买入
                    mStopProfit = Arith.add(bid, stopsLevel);
                    mStopLoss = Arith.sub(bid, stopsLevel);
                    noTVStopProfit.setText("≧ " + mStopProfit);
                    noTVStopLoss.setText("≦ " + mStopLoss);
                } else {
                    //卖出
                    mStopProfit = Arith.sub(ask, stopsLevel);
                    mStopLoss = Arith.add(ask, stopsLevel);
                    noTVStopLoss.setText("≧ " + mStopLoss);
                    noTVStopProfit.setText("≦ " + mStopProfit);
                }
            }
//            if (tag == 0) {
//                double margin = getMargin();
            double margin2 = CountClass.getMargin(type, noPendingTimes, askBidOne, askBidTwo, selectWhatNoPended, marginBase, marginChange, usdprex);
            if (margin2 == -1) return;
            Logger.e("accAmt:", accAmt + "  margin2: " + margin2);
            if (accAmt > margin2) {
                double accAmt2 = Arith.round(Arith.mul(accAmt, 0.8), 2);
                handMax = Arith.div2(Arith.mul(accAmt2, noPendingTimes), margin2, 2);
                handMax = Arith.div(handMax, minVolume, 0);//处理最小手数不定的情况
                handMax = Arith.mul(handMax, minVolume);
                buyMax = "|余额最大可买:" + handMax + "手";
                noIVRightAdd.setEnabled(true);
            } else {
                buyMax = "|余额最大可买:" + 0 + "手";
                noIVRightAdd.setEnabled(false);
            }
            marginAll = margin2;
            tvMargin.setText("需资金:$" + margin2 + buyMax);
//                tag = 1;
//            }

        }
    }

    /**
     * 品种保证金及止盈止损数据
     *
     * @param symbolInfo
     */
    public void setSymbolCalInfoDatas(SymbolInfo symbolInfo) {
        if (symbolInfo != null) {
            if (noTvCenterTimes == null) return;
            noTvCenterTimes.setText(symbolInfo.getMinVolume() + "");
            symbols = new String[]{symbol, symbolInfo.getMarginCalCurrency(), symbolInfo.getProfitCalCurrency()};
            minVolume = symbolInfo.getMinVolume();
            noPendingTimes = symbolInfo.getMinVolume();
            double stopsLe = (double) symbolInfo.getStopsLevel();
            digits = symbolInfo.getDigits();
            stopsLevel = Arith.div(stopsLe, Math.pow(10, digits), digits);
            double dd = Math.pow(10, digits);
            stopLossOrProfitVar = Arith.round3(Arith.div(1, dd), digits);
            type = symbolInfo.getType();
            marginBase = symbolInfo.getMarginBase();
            marginChange = symbolInfo.isMarginChange();
            profitChange = symbolInfo.isProfitChange();
            profitUSDPrex = symbolInfo.isProfitUSDPrex();
            usdprex = symbolInfo.isUsdprex();
            contracSize = symbolInfo.getContractSize();
            accAmt = symbolInfo.getAccAmt();
        }
    }

    /**
     * 必须加注解，否则无效
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventDatas event) {
        //1、直接买入，未设置止盈止损
        String ev = event.getTagOne();
        if (ev.equals(EventContents.STOCK_CHART_UPGRADE_ACTIVITY_ONE)) {
            if (handMax != 0) {
                submitTraderOpenData(0);
            } else {
                setPopupUnderMargin();
            }

        }

        //2、直接卖出，未设置止盈止损
        if (ev.equals(EventContents.STOCK_CHART_UPGRADE_ACTIVITY_TWO)) {
            if (handMax != 0) {
                submitTraderOpenData(1);

            } else {
                //弹出资金不足提示框
                setPopupUnderMargin();
            }

        }

        //3、设置止盈止损后
        if (ev.equals(EventContents.STOCK_CHART_UPGRADE_ACTIVITY_THREE)) {
            if (handMax != 0) {
                submitTraderOpenData(2);
            } else {
                //弹出资金不足提示框
                setPopupUnderMargin();
            }

        }

    }

    /**
     * 弹出资金不足提示框
     */
    private void setPopupUnderMargin() {
        View view = View.inflate(getContext(), R.layout.dialog_under_margin, null);
        TextView btnGoRecharge = (TextView) view.findViewById(R.id.btn_go_recharge);
        TextView btnEnsure = (TextView) view.findViewById(R.id.btn_ensure);
        btnGoRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), RechargeActivity.class));
                popupWindow.dismiss();
            }
        });
        btnEnsure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        isFinishActivity = false;
        showPopupWindow(view);
    }

    /**
     * 开仓前提示
     */
    private void submitTraderOpenData(final int where) {
        View view = View.inflate(getContext(), R.layout.pop_style_sure_orders, null);
        TextView tvItemName = (TextView) view.findViewById(R.id.tv_item_name);
        TextView tvBuyRise = (TextView) view.findViewById(R.id.tv_buy_rise);
        TextView tvHandTimes = (TextView) view.findViewById(R.id.tv_hand_times);
        TextView tvStopProfit = (TextView) view.findViewById(R.id.tv_stop_profit);
        TextView tvStopLoss = (TextView) view.findViewById(R.id.tv_stop_loss);
        TextView btnSure = (TextView) view.findViewById(R.id.btn_go_order);
        TextView btnCancle = (TextView) view.findViewById(R.id.btn_cancel);
        TextView tvBuyStatus = (TextView) view.findViewById(R.id.tv_buy_status);
        TextView tvHandsAndName = (TextView) view.findViewById(R.id.tv_hands_money_name);
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (where == 0)
                    stockChartPresenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbol, SpUtils.getInt(getContext(), "userId"), 0, (float) noPendingTimes, tp, sl);
                else if (where == 1)
                    stockChartPresenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbol, SpUtils.getInt(getContext(), "userId"), 1, (float) noPendingTimes, tp, sl);
                else if (where == 2)
                    stockChartPresenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbol, SpUtils.getInt(getContext(), "userId"), selectWhatNoPended, (float) noPendingTimes, tp, sl);
                popupWindow.dismiss();
            }
        });
        btnCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tvItemName.setText(symbolCn + " " + symbol);
        switch (where) {
            case 0:
                tvBuyRise.setText("买涨：" + BaseUtils.getDigitsData(ask, digits));
                tvBuyStatus.setText("买涨");
                tvBuyStatus.setBackgroundResource(R.drawable.yellow_text_bg);
                break;
            case 1:
                tvBuyRise.setText("买跌：" + BaseUtils.getDigitsData(bid, digits));
                tvBuyStatus.setText("买跌");
                tvBuyStatus.setBackgroundResource(R.drawable.green_text_bg);
                break;
            case 2:
                if (selectWhatNoPended == 0) {
                    tvBuyRise.setText("买涨：" + BaseUtils.getDigitsData(ask, digits));
                    tvBuyStatus.setText("买涨");
                    tvBuyStatus.setBackgroundResource(R.drawable.yellow_text_bg);
                } else {
                    tvBuyRise.setText("买跌：" + BaseUtils.getDigitsData(bid, digits));
                    tvBuyStatus.setText("买跌");
                    tvBuyStatus.setBackgroundResource(R.drawable.green_text_bg);

                }
                break;
        }

        tvHandTimes.setText("占用：" + "$" + marginAll);
        tvHandsAndName.setText(" " + noPendingTimes + "手 " + symbolCn);
        if (tp == 0) {
            tvStopProfit.setText("止盈：未设置");
        } else {
            tvStopProfit.setText("止盈：" + BaseUtils.getDigitsData(tp, digits));
        }
        if (sl == 0) {
            tvStopLoss.setText("止损：未设置");
        } else {
            tvStopLoss.setText("止损：" + BaseUtils.getDigitsData(sl, digits));

        }
        isFinishActivity = false;
        showPopupWindow(view);
    }

    /**
     * 展示开仓成功后返回信息
     */
    private void setPopupTraderOpenSuccess(OpenTrader openTrader) {
        showTime = 5000;
        View view = View.inflate(getContext(), R.layout.pop_buy_result, null);//pop_style_order_success
        TextView tvBuyResult = (TextView) view.findViewById(R.id.tv_buy_result);
        TextView tvBuyDetail = (TextView) view.findViewById(R.id.tv_buy_detail);
        LinearLayout llAll = (LinearLayout) view.findViewById(R.id.ll_all);
        tvBuyDetail.setText(openTrader.getSymbolCn() + " " + openTrader.getVolume() + "手[保证金$" + BaseUtils.getDigitsData(openTrader.getMargin(), 2) + "]，价格" + BaseUtils.getDigitsData(openTrader.getOpenPrice(), digits));
        if (openTrader.getCmd() == 0) {
            tvBuyResult.setText("已成功 " + "买入");
            llAll.setBackgroundResource(R.drawable.blue_text_bg);

        } else {
            tvBuyResult.setText("已成功 " + "卖出");
            llAll.setBackgroundResource(R.drawable.yellow_text_bg);
        }

        EventBus.getDefault().post(new EventDatas(EventContents.STOP_LOSS_OR_PROFIT_FINISH_TRADE, null));
        isFinishActivity = true;
        showPopupWindow(view);
        runnable = new Runnable() {
            @Override
            public void run() {
                showTime -= 1000;
                if (showTime == 0) {
                    handler.removeCallbacks(runnable);
                    popupWindow.dismiss();
                    getActivity().finish();

                } else
                    handler.postDelayed(runnable, 1000);
            }
        };
        handler.post(runnable);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void showDialog() {
        dialog = new MyProgressDialog(getContext());
        dialog.setCancelable(false);
        dialog.show();
    }

    @Override
    public void dismissDialog() {
        if (dialog != null)
            dialog.dismiss();
    }

    @Override
    public void showMyToast(String str) {
        Toast.makeText(getContext(), str, Toast.LENGTH_SHORT).show();
    }


    @Override
    public void setSymbolCalInfoData(SymbolInfo symbolInfo) {
    }

    /**
     * 开仓成功后返回值
     *
     * @param openTrader
     */
    @Override
    public void setTradeOpenData(OpenTrader openTrader) {
        setPopupTraderOpenSuccess(openTrader);
    }

    @Override
    public void setPendingOrderData(PendingOrder pendingOrder) {

    }

    @Override
    public void setSymbolPrice(SymbolPrice symbolPrice) {

    }

    /**
     * 交易手数 减
     */
    @OnClick(R.id.no_iv_left_sub)
    public void noIVLeftSub() {
        Logger.e("Test", "-------");
        if (noPendingTimes > minVolume) {
            noPendingTimes = Arith.sub(noPendingTimes, minVolume);
            noTvCenterTimes.setText(noPendingTimes + "");
            double margin = CountClass.getMargin(type, noPendingTimes, askBidOne, askBidTwo, selectWhatNoPended, marginBase, marginChange, usdprex);
            if (margin == -1) return;
            tvMargin.setText("需资金:$" + margin + buyMax);
            marginAll = margin;
        }

    }

    /**
     * 交易手数 加
     */
    @OnClick(R.id.no_iv_right_add)
    public void noIVRightAdd() {
        //先判断可买的最大手数，当满足条件后才执行下面操作
        Logger.e("Test", "++++++++");
        if (noPendingTimes < handMax) {
            noPendingTimes = Arith.add(noPendingTimes, minVolume);
            noTvCenterTimes.setText(noPendingTimes + "");
            double margin = CountClass.getMargin(type, noPendingTimes, askBidOne, askBidTwo, selectWhatNoPended, marginBase, marginChange, usdprex);
            if (margin == -1) return;
            tvMargin.setText("需资金:$" + margin + buyMax);
            marginAll = margin;
        }
    }

    /**
     * 设置止盈止损按钮
     */
    @OnClick(R.id.iv_set_lose_profit)
    public void ivSetLoseProfit() {

        if (isSetLoseOrProfit) {
            llStopLose.setVisibility(View.GONE);
            llStopProfit.setVisibility(View.GONE);
            noLLOrien.setVisibility(View.GONE);
            ivSetLoseProfit.setImageResource(R.mipmap.btn_normal);
            isSetLoseOrProfit = false;
        } else {
            llStopLose.setVisibility(View.VISIBLE);
            llStopProfit.setVisibility(View.VISIBLE);
            noLLOrien.setVisibility(View.VISIBLE);
            ivSetLoseProfit.setImageResource(R.mipmap.btn_click);
            isSetLoseOrProfit = true;
        }
        if (selectWhatNoPended == 0) {
            ((StockChartUpgradeActivity) getActivity()).setButtonStatus(false, isSetLoseOrProfit, selectWhatNoPended);
        } else {
            ((StockChartUpgradeActivity) getActivity()).setButtonStatus(false, isSetLoseOrProfit, selectWhatNoPended);
        }
    }

    /**
     * 买入按钮
     */
    @OnClick(R.id.no_ll_buy_rise)
    public void setNoLLBuyRise() {
        resetSomeVar();
        noLLBuyRise.setBackgroundResource(R.mipmap.bg_red_checked);
        noLLBuyFall.setBackgroundResource(R.mipmap.bg_no_check);
        selectWhatNoPended = 0;
        ((StockChartUpgradeActivity) getActivity()).setButtonStatus(false, isSetLoseOrProfit, selectWhatNoPended);

    }

    /**
     * 卖出按钮
     */
    @OnClick(R.id.no_ll_buy_fall)
    public void noLLBuyFall() {
        resetSomeVar();
        noLLBuyRise.setBackgroundResource(R.mipmap.bg_no_check);
        noLLBuyFall.setBackgroundResource(R.mipmap.bg_red_checked);
        selectWhatNoPended = 1;
        ((StockChartUpgradeActivity) getActivity()).setButtonStatus(false, isSetLoseOrProfit, selectWhatNoPended);

    }

    /**
     * 当更改买入状态时，重置一些参数
     */
    private void resetSomeVar() {
        tvLoss.setText("");
        tvProfit.setText("");
        stopLossTotal = 0;//止损的增量归零
        stopProfitTotal = 0;//止盈的增量归零
        noTVStopLossNum.setText("没有设置");
        noTVStopProfitNum.setText("没有设置");
        noIVStopLossSub.setEnabled(true);
        noIVStopLossAdd.setEnabled(true);
        noIVStopProfitSub.setEnabled(true);
        noIVStopProfitAdd.setEnabled(true);
    }

    /**
     * 未挂单开启止盈止损：止损 减
     */
    @OnClick(R.id.no_iv_stop_loss_sub)
    public void noIVStopLossSub() {
        noIVStopLossAdd.setEnabled(true);
        stopLossTotal = Arith.sub(stopLossTotal, stopLossOrProfitVar);
//        Log.e("Add", stopLossTotal + "");

        //判断当前是买入还是卖出
        if (selectWhatNoPended == 0) { //买入
            if (Arith.add(mStopLoss, stopLossTotal) < 0) return;
            sl = Arith.add(mStopLoss, stopLossTotal);
            noTVStopLossNum.setText(sl + "");
            double profit = CountClass.getProfit(sl, 0, askBidOne, askBidThree, contracSize, noPendingTimes, profitChange, profitUSDPrex);
            if (profit == -1) return;

            tvLoss.setText("预期盈亏：$" + profit);

        } else { //卖出
            if (stopLossTotal > 0) {
                sl = Arith.add(mStopLoss, stopLossTotal);
                noTVStopLossNum.setText(sl + "");
                double profit = CountClass.getProfit(sl, 1, askBidOne, askBidThree, contracSize, noPendingTimes, profitChange, profitUSDPrex);
                if (profit == -1) return;

                tvLoss.setText("预期盈亏：$" + profit);
            } else {
                stopLossTotal = 0;
            }
        }
        if (stopLossTotal == 0) {
            noIVStopLossSub.setEnabled(false);
            sl = 0;
            noTVStopLossNum.setText("没有设置");
            tvLoss.setText("止损不在范围内");
            return;
        }

    }

    /**
     * 未挂单开启止盈止损：止损 加
     */
    @OnClick(R.id.no_iv_stop_loss_add)
    public void noIVStopLossAdd() {
        noIVStopLossSub.setEnabled(true);
        stopLossTotal = Arith.add(stopLossTotal, stopLossOrProfitVar);
//        Log.e("Add", stopLossTotal + "");

        if (selectWhatNoPended == 0) { //买入
            if (stopLossTotal < 0) {
                sl = Arith.add(mStopLoss, stopLossTotal);
                noTVStopLossNum.setText(sl + "");
                double profit = CountClass.getProfit(sl, 0, askBidOne, askBidThree, contracSize, noPendingTimes, profitChange, profitUSDPrex);
                if (profit == -1) return;

                tvLoss.setText("预期盈亏：$" + profit);
            } else {
                stopLossTotal = 0;
            }

        } else {//卖出
            sl = Arith.add(mStopLoss, stopLossTotal);
            noTVStopLossNum.setText(sl + "");
            double profit = CountClass.getProfit(sl, 1, askBidOne, askBidThree, contracSize, noPendingTimes, profitChange, profitUSDPrex);
            if (profit == -1) return;

            tvLoss.setText("预期盈亏：$" + profit);

        }
        if (stopLossTotal == 0) {
            noIVStopLossAdd.setEnabled(false);
            sl = 0;
            noTVStopLossNum.setText("没有设置");
            tvLoss.setText("止损不在范围内");
            return;
        }

    }

    /**
     * 未挂单开启止盈止损：止盈 减
     */
    @OnClick(R.id.no_iv_stop_profit_sub)
    public void noIVStopoProfitSub() {
        noIVStopProfitAdd.setEnabled(true);
        stopProfitTotal = Arith.sub(stopProfitTotal, stopLossOrProfitVar);

        if (selectWhatNoPended == 0) {//买入
            if (stopProfitTotal > 0) {
                tp = Arith.add(mStopProfit, stopProfitTotal);
                noTVStopProfitNum.setText(tp + "");
                double profit = CountClass.getProfit(tp, 0, askBidOne, askBidThree, contracSize, noPendingTimes, profitChange, profitUSDPrex);
                if (profit == -1) return;

                tvProfit.setText("预期盈亏：$" + profit);
            } else {
                stopProfitTotal = 0;
            }
        } else {//卖出

            tp = Arith.add(mStopProfit, stopProfitTotal);
            noTVStopProfitNum.setText(tp + "");
            double profit = CountClass.getProfit(tp, 1, askBidOne, askBidThree, contracSize, noPendingTimes, profitChange, profitUSDPrex);
            if (profit == -1) return;

            tvProfit.setText("预期盈亏：$" + profit);
        }
        if (stopProfitTotal == 0) {
            noIVStopProfitSub.setEnabled(false);
            tp = 0;
            noTVStopProfitNum.setText("没有设置");
            tvProfit.setText("止盈不在范围内");
            return;
        }
    }

    /**
     * 未挂单开启止盈止损：止盈 加
     */
    @OnClick(R.id.no_iv_stop_profit_add)
    public void noIVStopProfitAdd() {
        noIVStopProfitSub.setEnabled(true);
        stopProfitTotal = Arith.add(stopProfitTotal, stopLossOrProfitVar);

        if (selectWhatNoPended == 0) {//买入
            tp = Arith.add(mStopProfit, stopProfitTotal);
            noTVStopProfitNum.setText(tp + "");
            double profit = CountClass.getProfit(tp, 0, askBidOne, askBidThree, contracSize, noPendingTimes, profitChange, profitUSDPrex);
            if (profit == -1) return;

            tvProfit.setText("预期盈亏：$" + profit);
        } else {//卖出
            if (stopProfitTotal < 0) {
                tp = Arith.add(mStopProfit, stopProfitTotal);
                noTVStopProfitNum.setText(tp + "");
                double profit = CountClass.getProfit(tp, 1, askBidOne, askBidThree, contracSize, noPendingTimes, profitChange, profitUSDPrex);
                if (profit == -1) return;

                tvProfit.setText("预期盈亏：$" + profit);
            } else {
                stopProfitTotal = 0;
            }
        }
        if (stopProfitTotal == 0) {
            noIVStopProfitAdd.setEnabled(false);
            tp = 0;
            noTVStopProfitNum.setText("没有设置");
            tvProfit.setText("止盈不在范围内");
            return;
        }

    }

    /**
     * 显示操作对话框
     *
     * @param mainView
     */
    public void showPopupWindow(View mainView) {
        popupWindow = new PopupWindow(mainView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.AnimationBottonAndTop);
        popupWindow.showAtLocation(View.inflate(getContext(), R.layout.activity_stock_chart, null), Gravity.BOTTOM, 0, 0);
        setBackgroundAlpha(0.7f);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1f);
                if (runnable != null && handler != null) {
                    handler.removeCallbacks(runnable);
                }
                if (isFinishActivity)
                    getActivity().finish();

            }
        });

    }

    /**
     * 设置popupwindow背景色
     *
     * @param bgAlpha
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
    }
}
